//
//  LSYNetBookController.m
//  LSYReader
//
//  Created by sam on 2018/3/29.
//  Copyright © 2018年 okwei. All rights reserved.
//
#import "EVEmptyView.h"
#import "WKProgressHUD.h"
#import "LSYNetBookCell.h"

#import "LSYParseModel.h"

#import "UIView+EV.h"
#import "UIColor+EV.h"
#import "NSString+EV.h"
#import "LSYRuleService.h"
#import "LSYNovelService.h"
#import "LSYNetBookController.h"
#import "LSYNetSourceController.h"
#import "LSYReadPageViewController.h"

@interface LSYNetBookController ()<LSYNetSourceControllerDelegate,UIGestureRecognizerDelegate> {
    LSYParseModel *_rule;
    EVEmptyView *_emptyView;
}
@property (nonatomic,strong) NSMutableArray *rules;
@property (nonatomic,strong) NSMutableArray *books;
@property (nonatomic,strong) UINavigationController *navController;
@end

@implementation LSYNetBookController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar addSubview:self.searchBar];
    [self.tableView registerNib:[UINib nibWithNibName:@"LSYNetBookCell" bundle:nil] forCellReuseIdentifier:@"LSYNetBookCell"];
    
    [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    [self loadRuels:^(NSMutableArray *rules) {
        _rule = rules.firstObject;
        NSString *ruleName = _rule.name?:@"";
        _searchBar.placeholder = ruleName;
        [_switchButton setTitle:ruleName forState:UIControlStateNormal];
        [WKProgressHUD dismissAll:YES];
    }];
    _emptyView = [self ev_showEmptyViewForType:EVEmptyViewDefault title:@"请输入关键字搜索书籍"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.searchBar.hidden = NO;
    self.searchBar.alpha = 1.f;
    [self.searchBar showCancelButton:NO animated:NO];
    [UIView animateWithDuration:0.2 animations:^{
        self.searchBar.alpha = 1.f;
    }];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.navigationController.viewControllers.count > 1) {
        self.searchBar.hidden = YES;
    }
    [UIView animateWithDuration:0.2 animations:^{
        self.searchBar.alpha = 0.f;
    }];
}

#pragma mark - logic
- (void)tapLeftBarButton {
    [UIView animateWithDuration:0.2 animations:^{
        self.searchBar.alpha = 0.f;
    }];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tapGesture:(UITapGestureRecognizer *)tapGesture {
    [UIView animateWithDuration:0.3 animations:^{
        _navController.view.ev_left = self.view.ev_width;
    } completion:^(BOOL finished) {
        [[self ev_emptyView] setUserInteractionEnabled:YES];
        [_navController.view removeFromSuperview];
        _navController = nil;
    }];
    if ([_searchBar.textField canResignFirstResponder]) {
        [_searchBar.textField resignFirstResponder];
    }
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (_navController) {
        return YES;
    }
    if ([_searchBar.textField isEditing]) {
        return YES;
    }
    return NO;
}

- (IBAction)listClicked:(UIButton *)btn {
    if([_searchBar.textField canResignFirstResponder]) {
        [_searchBar.textField resignFirstResponder];
    }
    LSYNetSourceController *ctr = [LSYNetSourceController netSourceController:self.rules];
    ctr.delegate   = self;
    _navController = [[UINavigationController alloc] initWithRootViewController:ctr];
    _navController.view.ev_left = self.view.ev_width;
    _navController.view.ev_width= 200;
    _navController.view.ev_height = [UIScreen mainScreen].bounds.size.height;
    _navController.view.layer.shadowColor = [UIColor colorWithRed:110/255.0 green:109/255.0 blue:124/255.0 alpha:1].CGColor;//阴影颜色
    _navController.view.layer.shadowOffset = CGSizeMake(-3, 3);//偏移距离
    _navController.view.layer.shadowOpacity = 0.8;//不透明度
    [self.navigationController.view addSubview:_navController.view];
    [_navController.navigationBar setBarStyle:UIBarStyleBlack];
    [_navController.navigationBar setBarTintColor:[UIColor ev_colorWithHex:0x2C2C2C]];
    [UIView animateWithDuration:0.3 animations:^{
        _navController.view.ev_left = self.view.ev_width - 200;
        [[self ev_emptyView] setUserInteractionEnabled:NO];
    }];
}
- (void)loadRuels:(void(^)(NSMutableArray *rules))block {
    if (_rules.count>0) {
        block(_rules);
    } else {
        [[LSYRuleService service] getRules:^(NSArray *rules) {
            _rules = [NSMutableArray arrayWithArray:rules];
            block(_rules);
        }];
    }
}

- (void)loadBooks {
    if (!_rule) {
        _rule = _rules.firstObject;
    }
    [WKProgressHUD showInView:self.view withText:@"加载中..." animated:YES];
    [self loadBooks:NO key:self.searchBar.text block:^(NSMutableArray *books) {
        [self.tableView reloadData];
        if (books.count>0) {
            [self hideEmptyView];
        } else {
            [[self ev_emptyView] setMainTitle:@"找不到书籍"];
        }
        [WKProgressHUD dismissAll:YES];
    }];
}

- (void)loadMoreBooks {
    [WKProgressHUD showInView:self.view withText:@"加载中..." animated:YES];
    [self loadBooks:YES key:self.searchBar.text block:^(NSMutableArray *books) {
        [self.tableView reloadData];
        if (books.count>0) {
            [self hideEmptyView];
        } else {
            [[self ev_emptyView] setMainTitle:@"找不到书籍"];
        }
        [WKProgressHUD dismissAll:YES];
    }];
}

- (void)loadBooks:(BOOL)isMore key:(NSString *)keyWord block:(void(^)(NSMutableArray *books))block {
    if (keyWord.length<=0) {
        _books = [NSMutableArray array];
        block(nil);
    } else {
        [LSYNovelService searchNovel:_rule key:keyWord  novels:^(NSArray *novels,NSString *moreUrl) {
            if (isMore) {
                [_books addObjectsFromArray:novels];
            } else {
                _books = [NSMutableArray arrayWithArray:novels];
            }
            block(_books);
        }];
    }
}

#pragma mark - UISearchBar
- (EVSearchBar *)searchBar
{
    if (_searchBar == nil)
    {
        _searchBar = [EVSearchBar loadSearBarWithFrame:CGRectMake(6.0, 7, SCREEN_WIDTH- 12, 30) style:SearchStyleGray];
        _searchBar.autoresizingMask = UIViewAutoresizingNone;
        _searchBar.delegate     = self;
        _searchBar.autoShowCancelButton = NO;
        _searchBar.placeholder  = @"输入关键词查找";
        [_searchBar setExclusiveTouch:YES];
    }
    return _searchBar;
}

#pragma mark - EVSearchBarDelegate Method
- (void)searchBarOnIcon:(EVSearchBar *)searchBar {
    [self tapLeftBarButton];
}

- (BOOL)searchBarShouldBeginEditingTextField:(EVSearchBar *)searchBar {
    if (_navController) {
        return NO;
    }
    return YES;
}
- (BOOL)searchBar:(EVSearchBar *)searchBar invalidInput:(NSString *)text
{
    return text.ev_trim.length > 0;
}

- (void)searchBarDidBeginEditingTextField:(EVSearchBar *)searchBar
{
    [searchBar showCancelButton:NO animated:NO];
}

- (void)searchBarShouldReturnTextField:(EVSearchBar *)searchBar
{
    if ([searchBar.textField canResignFirstResponder]) {
        [searchBar.textField resignFirstResponder];
    }
    //to search
    [self loadBooks];
}

#pragma mark - Table view
- (void)selectedRule:(LSYParseModel *)rule {
    _rule = rule;
    NSString *ruleName = _rule.name?:@"";
    _searchBar.placeholder = ruleName;
    [_switchButton setTitle:ruleName forState:UIControlStateNormal];
    [self tapGesture:nil];
    [self loadBooks];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.books.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSYNetBookCell *cell = (LSYNetBookCell *)[tableView dequeueReusableCellWithIdentifier:@"LSYNetBookCell" forIndexPath:indexPath];
    LSYBook *book = [self.books objectAtIndex:indexPath.row];
    [cell setBook:book];
    return cell;
}

#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
    LSYBook *book = self.books[indexPath.row];
    if ([_searchBar.textField canResignFirstResponder]) {
        [_searchBar.textField resignFirstResponder];
    }
    [LSYNovelService getChapters:book block:^(NSArray *chapters) {
        [WKProgressHUD dismissAll:YES];
        LSYReadModel *model = [[LSYReadModel alloc] initWithNetBook:book];
        LSYReadPageViewController *pageController = [[LSYReadPageViewController alloc] init];
        pageController.model = model;
        [self presentViewController:pageController animated:NO completion:nil];
    }];
}

- (void)viewDidLayoutSubviews {
    [_switchButton setImageLocation:kImageLocationLeft AlignmentCenterMode:kAlignmentCenterModeUnion Gap:2];
    _switchButton.ev_left = _searchBar.ev_width - _switchButton.ev_width;
    [_searchBar addSubview:_switchButton];
}

- (void)dealloc {
    _searchBar.delegate = nil;
    [_searchBar removeFromSuperview];
}
@end
